//
//  TKYUpdateProgressController.m
//  ProgressReportProject
//
//  Created by apple on 2018/4/23.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYUpdateProgressController.h"
#import "TKYSelectedView.h"
#import "TKYProgessView.h"
#import "TKYRemarkView.h"
#import "TKYUpdateProgressImageView.h"
#import "TKYAddPicButton.h"
#import "TKYDocListModel.h"
#import "ImageBrowserViewController.h"
#define NUMBERS @"0123456789\n"
@interface TKYUpdateProgressController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextFieldDelegate>{
     BOOL _isSelectedCamera;// 是否选择相机
}
/**
 提交按钮
 */
@property (nonatomic, strong)UIButton *submitButton;

/**
 图片view
 */
@property (nonatomic, strong)TKYUpdateProgressImageView *updateProgressImageView;

/**
 时间
 */
@property (nonatomic, strong)TKYSelectedView *dateView;
/**
 进度
 */
@property (nonatomic, strong)TKYProgessView *progessView;
/**
 工作量
 */
@property (nonatomic, strong)TKYSelectedView *workloadView;


/**
 pickerController
 */
@property (nonatomic, strong)UIImagePickerController *pickerController;
/**
 备注view
 */
@property (nonatomic, strong)TKYRemarkView *remarkView;

/**
 补充图片view
 */
@property (nonatomic, strong)TKYAddPicButton *addPicButtonView;


/**
 新增图片数组
 */
@property (nonatomic, strong)NSMutableArray *newImageArrM;

//图片的model数组
@property (nonatomic, strong)NSMutableArray *docListModelS;


/**
 参数
 */
/**
 图片
 */
@property (nonatomic, strong)NSMutableArray *progressImgList;

/**
 百分比
 */
@property (nonatomic, strong)NSString *percentStr;

/**
 工程量
 */
@property (nonatomic, strong)NSString *quantityStr;
/**
 备注
 */
@property (nonatomic, strong)NSString *remarkStr;


@end

@implementation TKYUpdateProgressController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestProgressReportInfoData];
    //设置界面
    [self setUI];
    NSLog(@"%@", self.progressModel.ID);

}

- (void)submitButtonClick:(UIButton *)button{
//    for (TKYDocListModel *docListModel  in self.docListModelS) {
//        [self.progressImgList addObject:docListModel.docPath];
//    }
    NSString *url = [NSString stringWithFormat:@"%@%@",kProgressApiBaseUrl, kupdateProgressUrl];
//    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
//    formatter.dateFormat=@"yyyy-MM-dd HH:mm:ss";
//    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
//    NSDate *date = [formatter dateFromString:self.progressModel.endDate];
    NSDictionary *parameterDict = @{
                                    @"id":self.progressModel.ID,
                                    @"token":[[NSUserDefaults standardUserDefaults] objectForKey:kToken],
                                    @"flowId":self.progressModel.flowId,
                                    @"flowName":self.progressModel.flowName,
                                    @"decomposeId":self.progressModel.decomposeId,
                                    @"endDateStr":self.progressModel.endDate,
                                    @"componentType":self.progressModel.componentType,
                                    @"percent":self.percentStr,
                                    @"quantities":[self strWithStr:self.quantityStr],
                                    @"remark":[self strWithStr:self.remarkStr],
                                    @"updator":[[NSUserDefaults standardUserDefaults] objectForKey:kUserID],
                                   // @"progressImgList":[self.progressImgList toReadableJSONString]
                                    };
    
    [SVProgressHUD showSVProgressHUDWithAnimationType:SVProgressHUDAnimationTypeFlat maskType:SVProgressHUDMaskTypeBlack style:SVProgressHUDStyleDark status:@"正在提交修改数据"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:url parameters:parameterDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < self.progressImgList.count; i ++) {
            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
            formatter.dateFormat=@"yyyyMMddHHmmss";
            NSString *str=[formatter stringFromDate:[NSDate date]];
            NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
            UIImage *image = self.progressImgList[i];
            UIImage *compreImage = [image scaleToWidth:1024];
            NSData *imageData = UIImageJPEGRepresentation(compreImage, 0.5);
            [formData appendPartWithFileData:imageData name:@"progressImgList" fileName:fileName mimeType:@"image/png"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"修改成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:responseObject[@"msg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"网络错误, 请稍候再试"];
    }];
}

/**
 请求详情数据
 */
- (void)requestProgressReportInfoData{
    NSString *url = [NSString stringWithFormat:@"%@%@id=%@&token=%@",kProgressApiBaseUrl, kProgressReportInfoUrl,self.progressModel.ID,[[NSUserDefaults standardUserDefaults]objectForKey:kToken]];
    [SVProgressHUD showWithStatus:@"正在请求数据"];
    [SVProgressHUD setBackgroundColor:[UIColor grayColor]];
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            self.docListModelS = [TKYDocListModel mj_objectArrayWithKeyValuesArray:response[@"docList"]];
            self.updateProgressImageView.docListModelS = self.docListModelS;
            [self.updateProgressImageView.collectionView reloadData];
        }else{
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:response[@"msg"]];
        }
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"网络错误,请稍候再试"];
    }];
}

- (void)setUI{
    self.navigationItem.title = @"进度修改";
    self.view.backgroundColor = [UIColor whiteColor];
    __weak typeof(self) weakSelf = self;
    //分部分项
   TKYSelectedView *subbranchView = [[TKYSelectedView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, kScreenWidth, kHeightScale *50) titleLabelText:@"分部分项" placeholderText:@"" imageName:@""];
    subbranchView.textField.text = self.progressModel.flowName;
    [self.view addSubview:subbranchView];
        
    //工序
   TKYSelectedView*processhView = [[TKYSelectedView alloc]initWithFrame:CGRectMake(0, subbranchView.kx_bottom, kScreenWidth, kHeightScale *50) titleLabelText:@"当前工序:" placeholderText:@"" imageName:@""];
    processhView.textField.text = self.progressModel.procedureName;
    [self.view addSubview:processhView];
    
    if ([self.progressModel.procedureName isEqualToString:@"灌砼"]) {
        //时间
        TKYSelectedView *dateView = [[TKYSelectedView alloc]initWithFrame:CGRectMake(0, processhView.kx_bottom, kScreenWidth, kHeightScale *50) titleLabelText:@"工序时间:" placeholderText:@"" imageName:@""];
        dateView.textField.text = self.progressModel.endDate;
        [self.view addSubview:dateView];
        
        //进度
        self.progessView = [[TKYProgessView alloc]initWithFrame:CGRectMake(0, dateView.kx_bottom, kScreenWidth, kHeightScale *50) titleLabelText:@"当前进度:" ];
        
        self.progessView.progressValue = self.progressModel.percent;
        self.progessView.progressLabel.text = [NSString stringWithFormat:@"%.lf%%",self.progessView.progressValue] ;
        self.percentStr = [NSString stringWithFormat:@"%ld",self.progressModel.percent];
        self.progessView.sprogressBlock = ^(UISlider *slide) {
            weakSelf.progessView.progressLabel.text = [NSString stringWithFormat:@"%.lf%%",slide.value];
            weakSelf.percentStr = [NSString stringWithFormat:@"%.lf",slide.value];
            
            NSString *URL = [NSString stringWithFormat:@"%@%@token=%@&flowId=%@&percent=%.lf",kProgressApiBaseUrl,kgetQuantityUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],weakSelf.progressModel.flowId,slide.value];
            NSString *urlUT = [URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [SVProgressHUD showWithStatus:@"正在计算工程量"];
            [KHttpRequestTool GET:urlUT parameters:nil success:^(id response) {
                NSLog(@"%@",response[@"msg"]);
                if ([response[@"code"] integerValue] == 0) {
                    NSNumber *quantity = response[@"quantity"];
                    CGFloat quantityFloat = [quantity floatValue];
                    weakSelf.workloadView.textField.text = [NSString  stringWithFormat:@"%.2f",quantityFloat];
                    weakSelf.quantityStr = [NSString  stringWithFormat:@"%.2f",quantityFloat];
                      [SVProgressHUD dismiss];
                }else{
                    [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:response[@"msg"]];
                }
              

            } failure:^(NSError *error) {
                
                NSLog(@"%@",error);
                [SVProgressHUD dismiss];
            }];
        };
        
        [self.view addSubview:self.progessView];
        
        //工作量
        TKYSelectedView *workloadView = [[TKYSelectedView alloc]initWithFrame:CGRectMake(0, self.progessView.kx_bottom, kScreenWidth, 50) titleLabelText:@"工作量" placeholderText:@"请输入" imageName:@""];
        workloadView.titleLabel.kx_height = 25;
        workloadView.textField.kx_height = 35;
        workloadView.selectedBtn.hidden = YES;
        workloadView.textField.delegate = self;
        self.workloadView = workloadView;
        [self.view addSubview:workloadView];
        
        //备注
        TKYRemarkView *remarkView = [[TKYRemarkView alloc]initWithFrame:CGRectMake(0, self.workloadView.kx_bottom, kScreenWidth, kHeightScale *100) titleLabelText:@"备注信息" remarkText:@""];
        remarkView.remarkTextView.text = self.progressModel.remark;
        remarkView.remarkTextBlock = ^(NSString *remarkText) {
            weakSelf.remarkStr = remarkText;
        };
        self.remarkView = remarkView;
        [self.view addSubview:remarkView];
        
        TKYAddPicButton *addPicButtonView = [[TKYAddPicButton alloc]initWithFrame:CGRectMake(0, remarkView.kx_bottom +5, kScreenWidth, kHeightScale *40) addPicTitleText:@"补充图片" addPicButtonTitle:@""];
        addPicButtonView.addPicButtonBlock = ^(UIButton *button) {
             if (self.docListModelS.count > 2) {
            KALERTSHOW(@"提示", @"只能选择三张图片", @"确定");
            return;
            }
            [weakSelf selectedCameraOrAlbum];
        };
        self.addPicButtonView = addPicButtonView;
        [self.view addSubview:addPicButtonView];
    }else{
        //时间
        TKYSelectedView *dateView = [[TKYSelectedView alloc]initWithFrame:CGRectMake(0, processhView.kx_bottom, kScreenWidth, kHeightScale *50) titleLabelText:@"工序时间:" placeholderText:@"" imageName:@""];
        self.dateView.frame = CGRectMake(0, processhView.kx_bottom, kScreenWidth, kHeightScale *50);
        dateView.textField.text = self.progressModel.endDate;
        [self.view addSubview:dateView];
        
        //进度
        self.progessView = [[TKYProgessView alloc]initWithFrame:CGRectMake(0, dateView.kx_bottom, kScreenWidth, kHeightScale *50) titleLabelText:@"当前进度:" ];
        
        self.progessView.progressValue = self.progressModel.percent;
        weakSelf.progessView.progressLabel.text = [NSString stringWithFormat:@"%.lf%%",self.progessView.progressValue] ;
        self.percentStr = [NSString stringWithFormat:@"%ld",self.progressModel.percent];
        self.progessView.sprogressBlock = ^(UISlider *slide) {
            weakSelf.progessView.progressLabel.text = [NSString stringWithFormat:@"%.lf%%",slide.value];
            weakSelf.percentStr = [NSString stringWithFormat:@"%.lf",slide.value];
            
            NSString *URL = [NSString stringWithFormat:@"%@%@token=%@&flowId=%@&percent=%.lf",kProgressApiBaseUrl,kgetQuantityUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],weakSelf.progressModel.flowId,slide.value];
            NSString *urlUT = [URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [SVProgressHUD showWithStatus:@"正在计算工程量"];
            [KHttpRequestTool GET:urlUT parameters:nil success:^(id response) {
                NSLog(@"%@",response[@"msg"]);
                if ([response[@"code"] integerValue] == 0) {
                    NSNumber *quantity = response[@"quantity"];
                    CGFloat quantityFloat = [quantity floatValue];
                    weakSelf.workloadView.textField.text = [NSString  stringWithFormat:@"%.2f",quantityFloat];
                    weakSelf.quantityStr = [NSString  stringWithFormat:@"%.2f",quantityFloat];
                }else{
                    [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:response[@"msg"]];
                }
                [SVProgressHUD dismiss];
                
            } failure:^(NSError *error) {
                
                NSLog(@"%@",error);
                [SVProgressHUD dismiss];
            }];
        };
        
        [self.view addSubview:self.progessView];
        
        //备注
        TKYRemarkView *remarkView = [[TKYRemarkView alloc]initWithFrame:CGRectMake(0, self.progessView.kx_bottom, kScreenWidth, kHeightScale *100) titleLabelText:@"备注信息" remarkText:@""];
        remarkView.remarkTextView.text = self.progressModel.remark;
        remarkView.remarkTextBlock = ^(NSString *remarkText) {
            weakSelf.remarkStr = remarkText;
        };
        self.remarkView = remarkView;
        [self.view addSubview:remarkView];
        
        TKYAddPicButton *addPicButtonView = [[TKYAddPicButton alloc]initWithFrame:CGRectMake(0, remarkView.kx_bottom +5, kScreenWidth, kHeightScale *40) addPicTitleText:@"补充图片" addPicButtonTitle:@""];
        addPicButtonView.addPicButtonBlock = ^(UIButton *button) {
             if (self.docListModelS.count > 2) {
            KALERTSHOW(@"提示", @"只能选择三张图片", @"确定");
            return;
            }
            [weakSelf selectedCameraOrAlbum];
        };
        self.addPicButtonView = addPicButtonView;
        [self.view addSubview:addPicButtonView];
        
    }
    [self.view addSubview:self.updateProgressImageView];
    [self.view addSubview:self.submitButton];
}

/**
 选择相机相册
 */
- (void)selectedCameraOrAlbum{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _isSelectedCamera = NO;
        self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.pickerController animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
         _isSelectedCamera = YES;
        self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark --- UINavigationControllerDelegate,UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //[self saveImage];
    if (_isSelectedCamera == YES) {
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }
    UIImage *compreImage = [image scaleToWidth:1024];
    NSData *data = UIImageJPEGRepresentation(compreImage, 0.5f);
    
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    TKYDocListModel *model = [[TKYDocListModel alloc]init];
    model.docPath = encodedImageStr;
    [self.docListModelS addObject:model];
    [self.progressImgList addObject:image];
        
    self.updateProgressImageView.docListModelS = self.docListModelS;
    [self.updateProgressImageView.collectionView reloadData];
   
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

//这个地方只做一个提示的功能
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    if (error) {
        
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    if (textField == self.workloadView.textField) {
        self.quantityStr = self.workloadView.textField.text;
        
        NSString *URL = [NSString stringWithFormat:@"%@%@token=%@&flowId=%@&quantity=%@",kProgressApiBaseUrl,kgetPercentUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],self.progressModel.flowId,self.workloadView.textField.text];
        NSString *urlUT = [URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [SVProgressHUD showWithStatus:@"正在计算百分比"];
        [KHttpRequestTool GET:urlUT parameters:nil success:^(id response) {
            NSLog(@"%@",response);
            if ([response[@"code"] integerValue] == 0) {
                NSNumber *percent = response[@"percent"];
                int percentInt = [percent intValue];
                self.progessView.progressValue = [percent integerValue];
                self.progessView.progressLabel.text = [NSString stringWithFormat:@"%.lf%%",self.progessView.progressValue];
                self.percentStr = [NSString stringWithFormat:@"%d",percentInt];
                
            }else{
                [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:response[@"msg"]];
            }
            [SVProgressHUD dismiss];
            
        } failure:^(NSError *error) {
            [SVProgressHUD dismiss];

            NSLog(@"%@",error);
        }];
    }
    //否则返回yes,不限制其他textfield
    return YES;
}

//只输入数字
- (BOOL)validateNumber:(NSString*)number {
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
    NSString *filtered = [[number componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [number isEqualToString:filtered];
    if(!basicTest)
    {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请求输入纯数字"];
        //输入了非法字符
        return NO;
    }
    return YES;
}

#pragma mark-- 懒加载
- (UIImagePickerController *)pickerController{
    if (!_pickerController) {
        UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
        pickerController.delegate = self;
        _pickerController=pickerController;
    }
    return _pickerController;
}

//
- (UIButton *)submitButton {
    if (_submitButton == nil) {
        _submitButton = [[UIButton alloc]initWithFrame:CGRectMake(kWidthScale  *20, kScreenHeight - kHeightScale *55 , kScreenWidth - kWidthScale *40, kHeightScale *40)];
        _submitButton.backgroundColor = KNavColor;
        [_submitButton dr_cornerWithRadius:5 backgroundColor:[UIColor whiteColor] borderColor:nil ];
        
        [_submitButton setTitle:@"提交" forState:UIControlStateNormal];
        [_submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_submitButton addTarget:self action:@selector(submitButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitButton;
}

//
- (TKYUpdateProgressImageView *)updateProgressImageView{
    if (_updateProgressImageView == nil) {
        _updateProgressImageView = [[TKYUpdateProgressImageView alloc]initWithFrame:CGRectMake(0, self.addPicButtonView.kx_bottom, kScreenWidth, kHeightScale *160)];
        _updateProgressImageView.backgroundColor = [UIColor redColor];
        __weak typeof(self) weakSelf = self;
        _updateProgressImageView.seletetedCollectionCellBlock = ^(NSIndexPath *indexPath) {

            [ImageBrowserViewController show:weakSelf type:PhotoBroswerVCTypeModal index:indexPath.item imagesBlock:^NSArray *{

                return [weakSelf getAllImage:weakSelf.docListModelS];
            }];
        };
    }
    return _updateProgressImageView;
}
//
- (NSMutableArray *)newImageArrM {
    if (_newImageArrM == nil) {
        _newImageArrM = [NSMutableArray array];
    }
    return _newImageArrM;
}

- (NSMutableArray *)progressImgList{
    if (_progressImgList == nil) {
        _progressImgList = [NSMutableArray array];
    }
    return _progressImgList;
}
//
- (NSMutableArray *)getAllImage:(NSArray *)docListModelS{
    NSMutableArray *imageArr = [NSMutableArray array];
    for (TKYDocListModel *docListModel in docListModelS) {
        UIImage *image = [UIImage imageWithData:[[NSData alloc]initWithBase64EncodedString:docListModel.docPath options:(NSDataBase64DecodingIgnoreUnknownCharacters)]];
        [imageArr addObject:image];
    }
    return imageArr.copy;
}
//
- (NSString *)strWithStr:(NSString *)str{
    NSString *newStr = [NSString string];
    if (str.length == 0) {
        newStr = @"";
    }else{
        newStr = str;
    }
    return newStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
